#ifndef unigame_AutoRelease_h
#define unigame_AutoRelease_h

#include <list>
#include "config/Def.h"

namespace unigame
{
	class AutoRelease
	{
	public:
		virtual ~AutoRelease()
		{
		}

		virtual void retain()
		{
			++m_referenceCount;
		}

		virtual void release()
		{
			--m_referenceCount;
			if(m_referenceCount == 0 && !m_next)
			{
				addToDestroy();
			}
		}

		virtual int32u referenceCount()
		{
			return m_referenceCount;
		}

		static void clear();

		static bool isEmpty()
		{
			return !s_head && !s_deleteHead;
		}

	protected:
		AutoRelease():m_referenceCount(0), m_next(0)
		{
			addToDestroy();
		}

		void addToDestroy();

	protected:
		int32u m_referenceCount;
		AutoRelease* m_next;

		static AutoRelease* s_head;
		static AutoRelease* s_end;
		static AutoRelease* s_deleteHead;
		static AutoRelease* s_deleteEnd;
		static bool s_isLock;
	};
}

#endif